import 'dart:convert';

import 'package:ecy_app_flutter/EcyRouter.dart';
import 'package:ecy_app_flutter/ecycommon/utils/EcyLogger.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../../constant/EcyEventConsnt.dart';
import '../../../ecycommon/EcyEventBus.dart';
import '../../../ecycommon/EcyRequestBaseManager.dart';
import '../../../model/EcyApiCommonPage.dart';
import '../../../model/EcyApiCommonResponse.dart';
import '../../../model/EcyLocationModel.dart';

class EcyAddressPage extends StatefulWidget {

  bool checkFlag = false;
  String? locationId;

  EcyAddressPage(this.checkFlag, this.locationId);

  @override
  _EcyAddressPageState createState() => _EcyAddressPageState();
}

class _EcyAddressPageState extends State<EcyAddressPage> {

  _EcyAddressPageState();

  var _defaultAddressIndex = 0;
  late ScrollController _scrollController;
  late List<EcyLocationModel> _ecyLocationModelList = [];
  late String _selectedId;

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    _selectedId = widget.locationId ?? "";
    requestData();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void deactivate() {
    super.deactivate();
    EcyLogger.log("deactivate" + "EcyMyPage");
  }

  @override
  Future<void> requestData({int pageIndex = 1, int type = 0}) async {
    Map<String, dynamic> body = {
      "pageSize": 50,
      "pageIndex": pageIndex,
    };
    var response = await EcyRequestbasemanager()
        .get("/app/api/app/user/address/list", body);
    if (response != null) {
      var _respModel =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (_respModel.code == 0 || _respModel.code == 200) {
        EcyApiCommonPage<EcyLocationModel> _modelPage =
            EcyApiCommonPage.fromJson(
                response["data"], (json) => EcyLocationModel.fromJson(json));
        setState(() {
          _ecyLocationModelList = _modelPage.records ?? [];
          _defaultAddressIndex =
              _ecyLocationModelList.indexWhere((e) => e.addressDefault == 1);
        });
      }
    }
  }

  void _setAddressDefault(EcyLocationModel locationModel) async {
    Map<String, dynamic> body = {
      "id": locationModel.id,
      "addressDefault": 1,
      "contact": locationModel.contact,
      "phone": locationModel.phone,
      "detail": locationModel.detail,
      "province": locationModel.provinceId,
      "city": locationModel.cityId,
      "area": locationModel.areaId,
      "street": locationModel.areaId,
      "address": locationModel.detail,
    };
    try {
      var response = await EcyRequestbasemanager()
          .put('/app/api/app/user/address/${locationModel.id}', body);
      if (response != null) {
        var _RespModel =
        EcyApiCommonResponse.fromJson(response, (response) => json);
        if (_RespModel.code == 0 || _RespModel.code == 200) {
          EasyLoading.showToast("已设为默认", duration: Duration(seconds: 1));
          //发送全局通知
          EcyEventBus().emit(EcyEventConst.kAddressEdit);
        } else {
          EasyLoading.showToast(_RespModel.msg ?? "请稍后再试", duration: Duration(seconds: 2));
        }
      }
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: Duration(seconds: 2));
    }
  }

  // 弹出对话框
  Future<bool?> showDeleteConfirmDialog(String content) {
    return showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          // title: const Text(''),
          contentPadding: const EdgeInsets.all(0),
          backgroundColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8.0),
          ),
          content: SizedBox(
            height: 130,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Padding(
                  padding: const EdgeInsets.only(top: 20, bottom: 30),
                  child: Text(
                    content,
                    style: const TextStyle(fontSize: 18),
                  ),
                ),
                const Divider(height: 0, color: Color(0XFFdcdcdc)),
                SizedBox(
                  height: 50,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: DecoratedBox(
                          decoration: const BoxDecoration(
                              border: Border(
                            right: BorderSide(
                              width: 1.0,
                              color: Color(0XFFdcdcdc),
                            ),
                          )),
                          child: TextButton(
                            style: const ButtonStyle(
                              alignment: Alignment.center,
                            ),
                            child: const Text(
                              '取消',
                              style:
                                  TextStyle(fontSize: 18, color: Colors.black),
                            ),
                            onPressed: () =>
                                Navigator.of(context).pop(), // 关闭对话框
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: TextButton(
                          child: const Text(
                            '确认',
                            style: TextStyle(
                                fontSize: 18, color: Color(0xFFEA4B9B)),
                          ),
                          onPressed: () {
                            //关闭对话框并返回true
                            Navigator.of(context).pop(true);
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          actionsAlignment: MainAxisAlignment.spaceAround,
          actionsPadding: const EdgeInsets.all(0),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F5),
      appBar: AppBar(
          //导航栏
          backgroundColor: Colors.white,
          leadingWidth: 50.w,
          leading: GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              EcyRouter.pop(context, "");
            },
            child: Align(
              alignment: Alignment.centerRight,
              child: Image.asset(
                "assets/images/ic_back.png",
                width: 30.w,
              ),
            ),
          ),
          titleSpacing: 0,
          title: Text('收货地址',
              style: TextStyle(
                  fontFamily: "PingFang SC",
                  fontWeight: FontWeight.w700,
                  fontSize: 16.sp,
                  color: const Color(0xFF262626))),
          centerTitle: true,
          actions: [
            GestureDetector(
                onTap: () {
                  EcyRouter()
                      .push(context, EcyRouter.addressEditPage,
                          EcyLocationModel.fromJson({}))
                      .then((val) => requestData());
                },
                child: Container(
                  margin: EdgeInsets.only(
                      left: 8.w, right: 16.w, top: 8.h, bottom: 8.h),
                  child: Text('新增',
                      style: TextStyle(
                          fontFamily: "PingFang SC",
                          fontWeight: FontWeight.w700,
                          fontSize: 16.sp,
                          color: const Color(0xFF262626))),
                ))
          ]),
      body: SizedBox(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          // color: Colors.white,
          child: Padding(
            padding: const EdgeInsets.all(8),
            child: _ecyLocationModelList.isEmpty
                ? _emptyPage()
                : _addressListPage(),
          )),
    );
  }

  Widget _addressListPage() {
    return ListView.builder(
      controller: _scrollController,
      physics: const AlwaysScrollableScrollPhysics(),
      itemCount: _ecyLocationModelList.length,
      itemBuilder: (context, index) {
        var ecyLocationModel = _ecyLocationModelList[index];
        return _buildAddressCard(ecyLocationModel, index);
      },
    );
  }

  Widget _buildAddressCard(EcyLocationModel locationModel, index) {
    return DecoratedBox(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8.0), //3像素圆角
          border: _selectedId == locationModel.id && widget.checkFlag
              ? Border.all(
                  color: const Color(0xFFEA4B9B),
                  width: 1,
                )
              : null,
        ),
        child: Card(
          color: Colors.white,
          elevation: 0,
          // margin: const EdgeInsets.only(bottom: 10),
          child: Padding(
            padding: const EdgeInsets.fromLTRB(15, 15, 15, 10),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                GestureDetector(
                    child: Container(
                      color: Colors.white,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text('${locationModel.contact}',
                                  style: TextStyle(
                                      fontSize: 14.sp,
                                      fontWeight: FontWeight.bold),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis),
                              Text('${locationModel.phone}',
                                  style: TextStyle(
                                      fontSize: 14.sp,
                                      fontWeight: FontWeight.bold),
                                  overflow: TextOverflow.ellipsis),
                            ],
                          ),
                          const Padding(padding: EdgeInsets.only(top: 6)),
                          Padding(
                            padding: const EdgeInsets.only(bottom: 8),
                            child: Text(
                                '${locationModel.provinceName} ${locationModel.cityName} ${locationModel.areaName} ${locationModel.detail}',
                                maxLines: 2,
                                style: TextStyle(
                                    fontSize: 14.sp,
                                    color: const Color(0xFF8C8C8C)
                                        .withOpacity(0.8)),
                                textAlign: TextAlign.left),
                          ),
                          const Padding(
                            padding: EdgeInsets.only(bottom: 8),
                            child: Divider(height: 1, color: Color(0XFFF5F5F5)),
                          ),
                        ],
                      ),
                    ),
                    onTap: () {
                      if(widget.checkFlag) {
                        setState(() {
                          _selectedId = locationModel.id ?? "";
                          Navigator.of(context).pop(locationModel);
                        });
                      }
                    }),
                Row(mainAxisAlignment: MainAxisAlignment.start, children: [
                  Expanded(
                    flex: 1,
                    child: GestureDetector(
                      onTap: () {
                        setState(() {
                          _defaultAddressIndex = index;
                        });
                        _setAddressDefault(locationModel);
                      },
                      child: Row(
                        children: [
                          Image(
                              image: AssetImage(_defaultAddressIndex == index
                                  ? 'assets/images/login_checked.png'
                                  : 'assets/images/login_unchecked.png'),
                              width: 20.w,
                              height: 20.w),
                          Padding(
                            padding: const EdgeInsets.only(left: 3),
                            child: Text('默认地址',
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                    fontFamily: "PingFang SC",
                                    fontWeight: FontWeight.w500,
                                    fontSize: 14.sp,
                                    color: _defaultAddressIndex == index
                                        ? Color(0xFFEA4B9B)
                                        : Color(0xFF8C8C8C))),
                          ),
                        ],
                      ),
                    ),
                  ),
                  Expanded(
                    flex: 2,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        GestureDetector(
                            onTap: () async {
                              bool? delete =
                                  await showDeleteConfirmDialog('您确定要删除吗？');
                              if (delete != null && delete) {
                                // Map<String, dynamic> body = {'ids': [locationModel.id]};
                                var response = await EcyRequestbasemanager()
                                    .delete('/app/api/app/user/address',
                                        [locationModel.id]);
                                if (response != null) {
                                  EasyLoading.showToast("删除成功",
                                      duration: Duration(seconds: 1));

                                  var _RespModel =
                                      EcyApiCommonResponse.fromJson(
                                          response, (response) => json);
                                  if (_RespModel.code == 0 ||
                                      _RespModel.code == 200) {
                                    requestData();
                                  }
                                }
                              }
                            },
                            child: Row(
                              children: [
                                const Icon(
                                  Icons.delete,
                                  color: Colors.grey,
                                  size: 20,
                                ),
                                Text(
                                  "删除",
                                  style: TextStyle(
                                    fontFamily: "PingFang SC",
                                    fontWeight: FontWeight.w500,
                                    fontSize: 14.sp,
                                    color: const Color(0xFF8C8C8C),
                                  ),
                                ),
                              ],
                            )),
                        const Padding(padding: EdgeInsets.only(right: 15)),
                        GestureDetector(
                            onTap: () {
                              EcyRouter()
                                  .push(context, EcyRouter.addressEditPage,
                                      locationModel)
                                  .then((val) => val ? requestData() : null);
                            },
                            child: Row(
                              children: [
                                const Icon(
                                  Icons.edit_outlined,
                                  color: Colors.grey,
                                  size: 20,
                                ),
                                Text(
                                  "编辑",
                                  style: TextStyle(
                                    fontFamily: "PingFang SC",
                                    fontWeight: FontWeight.w500,
                                    fontSize: 14.sp,
                                    color: const Color(0xFF8C8C8C),
                                  ),
                                ),
                              ],
                            )),
                      ],
                    ),
                  ),
                ]),
              ],
            ),
          ),
        ));
  }

  Widget _emptyPage() {
    return SingleChildScrollView(
        controller: _scrollController,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            const Padding(padding: EdgeInsets.only(bottom: 60)),
            Image.asset('assets/images/empty/ic_empty_orders.png',
                width: 200, height: 200),
            Text('要寄往哪里呢',
                style: TextStyle(
                    fontFamily: "PingFang SC",
                    fontWeight: FontWeight.w500,
                    fontSize: 14.sp,
                    color: const Color(0xFF262626))),
            const Padding(padding: EdgeInsets.only(bottom: 30)),
            SizedBox(
              // height: 38.h,
              width: MediaQuery.of(context).size.width / 2.5,
              child: TextButton(
                  onPressed: () {
                    EcyRouter()
                        .push(context, EcyRouter.addressEditPage,
                            EcyLocationModel.fromJson({}))
                        .then((val) => val ? requestData() : null);
                  },
                  style: const ButtonStyle(
                    alignment: Alignment.center,
                    foregroundColor: WidgetStatePropertyAll(Color(0xFFEA4B9B)),
                    side: WidgetStatePropertyAll(
                        BorderSide(color: Color(0xFFEA4B9B), width: 1)),
                    overlayColor: WidgetStatePropertyAll(Colors.transparent),
                  ),
                  child: Text(
                    '添加收货地址',
                    style: TextStyle(
                      fontFamily: "PingFang SC",
                      fontWeight: FontWeight.w400,
                      fontSize: 14.sp,
                      leadingDistribution:
                          TextLeadingDistribution.even, // 设置leading策略
                    ),
                  )),
            ),
          ],
        ));
  }
}
